<template>
  <div>
    <el-button type="primary" @click="createConnection">Primary</el-button>
    <el-button type="success" @click="doSubscribe">订阅主题</el-button>
    <el-button type="info" @click="doUnSubscribe">取消订阅</el-button>
    <el-button type="primary" plain @click="doPublish">消息发布</el-button>
    <el-button type="info" plain @click="destroyConnection">断开连接</el-button>
  </div>
</template>

<!-- <script setup>
import mqtt from "mqtt";
import { ref, onMounted } from "vue";

console.log('mqtt >>> ', mqtt)

const connection = {
  protocol: "ws",
  host: "broker.emqx.io",
  // ws: 8083; wss: 8084
  port: 8083,
  endpoint: "/mqtt",
  // for more options, please refer to https://github.com/mqttjs/MQTT.js#mqttclientstreambuilder-options
  clean: true,
  connectTimeout: 30 * 1000, // ms
  reconnectPeriod: 4000, // ms
  clientId: "emqx_vue_" + Math.random().toString(16).substring(2, 8),
  // auth
  username: "emqx_test",
  password: "emqx_test",
};

const subscription = {
  topic: "topic/mqttx",
  qos: 0,
};

const publish = {
  topic: "topic/browser",
  qos: 0,
  payload: '{ "msg": "Hello, I am browser." }',
};

const receiveNews = "";
const qosList = [0, 1, 2];
const client = {
  connected: false,
};
const subscribeSuccess = false;
const connecting = false;
const retryTimes = 0;
</script> -->

<script>
import mqtt from "mqtt";

export default {
  data() {
    return {
      connection: {
        protocol: "ws",
        host: "broker.emqx.io",
        // ws: 8083; wss: 8084
        port: 8083,
        endpoint: "/mqtt",
        // for more options, please refer to https://github.com/mqttjs/MQTT.js#mqttclientstreambuilder-options
        clean: true,
        connectTimeout: 30 * 1000, // ms 超时时间
        reconnectPeriod: 4000, // ms 重连时间间隔
        clientId: "emqx_vue_" + Math.random().toString(16).substring(2, 8),
        // auth
        username: "emqx_test",
        password: "emqx_test",
      },
      // 订阅
      subscription: {
        topic: "topic/mqttx",
        qos: 0,
      },
      // 消息发布
      publish: {
        topic: "topic/browser",
        qos: 0,
        payload: '{ "msg": "Hello, I am browser." }',
      },
      receiveNews: "",
      qosList: [0, 1, 2],
      client: {
        connected: false,
      },
      subscribeSuccess: false,
      connecting: false,
      retryTimes: 0,
    };
  },

  methods: {
    initData() {
      this.client = {
        connected: false,
      };
      this.retryTimes = 0;
      this.connecting = false;
      this.subscribeSuccess = false;
    },
    handleOnReConnect() {
      this.retryTimes += 1;
      if (this.retryTimes > 5) {
        try {
          this.client.end();
          this.initData();
          this.$message.error("Connection maxReconnectTimes limit, stop retry");
        } catch (error) {
          this.$message.error(error.toString());
        }
      }
    },
    createConnection() {
      try {
        this.connecting = true;
        const { protocol, host, port, endpoint, ...options } = this.connection;
        const connectUrl = `${protocol}://${host}:${port}${endpoint}`;
        console.log(connectUrl);
        this.client = mqtt.connect(connectUrl, options);
        console.log('client >>> ', this.client);
        if (this.client.on) {
          this.client.on("connect", (e) => {
            this.connecting = false;
            console.log("Connection succeeded!", e);
          });
          this.client.on("reconnect", this.handleOnReConnect);
          this.client.on("error", (error) => {
            console.log("Connection failed", error);
          });
          this.client.on("message", (topic, message) => {
            this.receiveNews = this.receiveNews.concat(message);
            console.log(`Received message ${message} from topic ${topic}`);
          });
        }
      } catch (error) {
        this.connecting = false;
        console.log("mqtt.connect error", error);
      }
    },
    // 订阅主题
    doSubscribe() {
      const { topic, qos } = this.subscription;
      this.client.subscribe(topic, { qos }, (error, res) => {
        if (error) {
          console.log("Subscribe to topics error", error);
          return;
        }
        this.subscribeSuccess = true;
        console.log("Subscribe to topics res", res);
      });
    },
    // 取消订阅
    doUnSubscribe() {
      const { topic } = this.subscription;
      this.client.unsubscribe(topic, (error) => {
        if (error) {
          console.log("Unsubscribe error", error);
        }
      });
    },
    // 消息发布
    doPublish() {
      const { topic, qos, payload } = this.publish;
      this.client.publish(topic, payload, { qos }, (error) => {
        if (error) {
          console.log("Publish error", error);
        }
      });
    },
    // 断开连接
    destroyConnection() {
      if (this.client.connected) {
        try {
          this.client.end(false, () => {
            this.initData();
            console.log("Successfully disconnected!");
          });
        } catch (error) {
          console.log("Disconnect failed", error.toString());
        }
      }
    },
  },
  mounted() {
    this.initData()
    // this.handleOnReConnect()
    this.createConnection()
    // console.log(process.env);
    // console.log(import.meta.env.MODE);
  }
};
</script>


<style lang="scss" scoped>
</style>